import { ref, watch, onMounted, nextTick, computed } from 'vue'
import * as monaco from 'monaco-editor'

export type ThemeMode = 'light' | 'dark' | 'system'

export function useTheme() {
  // 主题模式，默认跟随系统
  const themeMode = ref<ThemeMode>('system')
  const isInitialized = ref(false)

  // 计算当前是否为深色模式
  const isDark = computed(() => {
    if (themeMode.value === 'system') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    return themeMode.value === 'dark'
  })

  // 计算当前实际主题
  const currentTheme = computed(() => (isDark.value ? 'dark' : 'light'))

  // 切换主题模式
  function toggleTheme() {
    // 循环切换：system -> light -> dark -> system
    if (themeMode.value === 'system') {
      setTheme('light')
    } else if (themeMode.value === 'light') {
      setTheme('dark')
    } else {
      setTheme('system')
    }
  }

  // 设置特定主题模式
  function setTheme(mode: ThemeMode) {
    themeMode.value = mode
    updateTheme()
    saveTheme()
  }

  // 更新DOM类名和Monaco主题
  function updateTheme() {
    try {
      const htmlElement = document.documentElement

      // 移除所有主题类
      htmlElement.classList.remove('light', 'dark')

      // 添加当前主题类
      htmlElement.classList.add(currentTheme.value)

      // 设置主题到meta标签，便于SEO和无障碍访问
      const themeColorMeta = document.querySelector('meta[name="theme-color"]')
      if (themeColorMeta) {
        themeColorMeta.setAttribute('content', isDark.value ? '#171717' : '#ffffff')
      }

      // 延迟更新Monaco主题，确保DOM更新完成
      nextTick(() => {
        if (monaco && monaco.editor) {
          try {
            const monacoTheme = isDark.value ? 'vs-dark' : 'vs'
            monaco.editor.setTheme(monacoTheme)
          } catch (error) {
            console.warn('Failed to update Monaco theme:', error)
          }
        }
      })

      // 触发自定义事件，通知其他组件主题已更改
      window.dispatchEvent(
        new CustomEvent('themeChanged', {
          detail: { theme: currentTheme.value, mode: themeMode.value },
        }),
      )
    } catch (error) {
      console.error('Failed to update theme:', error)
    }
  }

  // 保存主题设置到localStorage
  function saveTheme() {
    try {
      localStorage.setItem('theme-mode', themeMode.value)
    } catch (error) {
      console.warn('Failed to save theme preference:', error)
    }
  }

  // 从localStorage加载主题设置
  function loadTheme() {
    try {
      const saved = localStorage.getItem('theme-mode')
      if (saved && ['light', 'dark', 'system'].includes(saved)) {
        themeMode.value = saved as ThemeMode
      }
    } catch (error) {
      console.warn('Failed to load theme preference:', error)
    }
  }

  // 强制重新应用主题
  function forceUpdateTheme() {
    // 先移除所有主题类
    document.documentElement.classList.remove('dark', 'light')

    // 短暂延迟后重新应用
    setTimeout(() => {
      updateTheme()
    }, 10)
  }

  // 获取系统主题
  function getSystemTheme(): 'light' | 'dark' {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }

  // 初始化主题
  onMounted(async () => {
    await nextTick()

    // 加载保存的主题设置
    loadTheme()

    // 确保DOM完全准备好后再设置主题
    setTimeout(() => {
      updateTheme()
      isInitialized.value = true
    }, 50)
  })

  // 监听系统主题变化
  let systemThemeTimeout: number
  const systemThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

  function handleSystemThemeChange() {
    // 只有在主题模式为system时才响应系统主题变化
    if (themeMode.value === 'system') {
      // 防抖系统主题变化
      clearTimeout(systemThemeTimeout)
      systemThemeTimeout = setTimeout(() => {
        updateTheme()
      }, 200)
    }
  }

  // 添加系统主题变化监听器
  systemThemeMediaQuery.addEventListener('change', handleSystemThemeChange)

  // 组件卸载时清理监听器
  onUnmounted(() => {
    systemThemeMediaQuery.removeEventListener('change', handleSystemThemeChange)
    clearTimeout(systemThemeTimeout)
  })

  // 监听主题模式变化
  watch(themeMode, () => {
    updateTheme()
    saveTheme()
  })

  // 监听媒体查询变化（兼容性处理）
  watch(() => window.matchMedia('(prefers-color-scheme: dark)').matches, handleSystemThemeChange, {
    immediate: false,
  })

  return {
    themeMode,
    isDark,
    isInitialized,
    currentTheme,
    toggleTheme,
    setTheme,
    updateTheme,
    forceUpdateTheme,
    getSystemTheme,
  }
}

// 为了支持onUnmounted，我们需要导入它
import { onUnmounted } from 'vue'
